package silo.dungeonbuddy;

import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

import javax.imageio.ImageIO;

/**
 * A resource manager for sprites.
 */
public class SpriteStore
{
	//The single instance of this class
	private static SpriteStore single = new SpriteStore();
	
	public static SpriteStore get()
	{
		return single;
	}
	
	//The cached sprite map, from reference to sprite instance
	private HashMap sprites = new HashMap();

	public Sprite getSprite(String ref)
	{
		// if the sprite is already in the cache
		// then just return the existing version
		if (sprites.get(ref) != null)
		{
			return (Sprite) sprites.get(ref);
		}
		
		// otherwise, grab the sprite from the resource loader
		BufferedImage sourceImage = null;
		
		try
		{
			// ClassLoader.getResource() to ensure the resource is
			// loaded from the right place
			URL url = this.getClass().getClassLoader().getResource(ref);
			
			if (url == null)
			{
				fail("Can't find ref: "+ref);
			}
			
			// ImageIO to read in the image
			sourceImage = ImageIO.read(url);
		} catch (IOException e)
		{
			fail("Failed to load: "+ref);
		}
		
		// create an accelerated image of the right size to store our sprite in
		GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
		Image image = gc.createCompatibleImage(sourceImage.getWidth(),sourceImage.getHeight(),Transparency.BITMASK);
		
		// draw the source image into the accelerated image
		image.getGraphics().drawImage(sourceImage,0,0,null);
		
		// create a sprite, add it the cache then return it
		Sprite sprite = new Sprite(image);
		sprites.put(ref,sprite);
		
		return sprite;
	}

	private void fail(String message)
	{
		//IF FAILURE, PRINT ERROR MESSAGE
		System.out.println(message);
	}
}